package com.lancoo.znbkxx.teacher.ui.activity

import android.annotation.SuppressLint
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.Ext.Companion.COURSE_CLASSID
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.QuestionListAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseVMActivity
import com.lancoo.znbkxx.teacher.databinding.ActivityPublishBinding
import com.lancoo.znbkxx.teacher.ui.fragment.*
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.viewmodel.HardSolutionViewModel
import com.lancoo.znbkxx.teacher.widget.LogOutDialog

import kotlinx.android.synthetic.main.activity_publish.*
import java.math.BigDecimal

/**
 * @author : Admin
 * @date   : 2019/8/5 14:26
 * @desc   :
 */
class CommentDetailActivity : BaseVMActivity<HardSolutionViewModel, ActivityPublishBinding>(),
        View.OnClickListener {
    private val isOneOnOne by lazy { intent.getBooleanExtra("isOneOnOne", false) }
    private val quesId by lazy { intent.getStringExtra("QuesID") }
    private val paperId by lazy { intent.getStringExtra("PaperID") }
    private val setId by lazy { intent.getStringExtra("SetID") }
    private val paperName by lazy { intent.getStringExtra("PaperName") }
    private val finished by lazy { intent.getBooleanExtra("isCommented", false) }
    private lateinit var fTransition: FragmentTransaction
    private var currentFragment = Fragment()
    private val commentFragment by lazy {
        CommentDetailFragment.newInstance(if (isOneOnOne) "" else paperName!!, isOneOnOne)
    }
    private val detailFragment by lazy { StuAnswerDetailFragment.newInstance(quesId) }

    //    private val ft by lazy {
//        supportFragmentManager.beginTransaction()
//            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
//    }
    private val publishFragment by lazy {
        supportFragmentManager.findFragmentByTag(
                "comment")!!.childFragmentManager.findFragmentByTag(
                "publish"
        ) as PublishFragment
    }
    private var state: Int = -1


    override fun providerVMClass(): Class<HardSolutionViewModel>? {
        return HardSolutionViewModel::class.java
    }

    override fun setLayoutID(): Int {
        return R.layout.activity_publish
    }

    override fun initView() {
        binding.ivDetail.setOnClickListener(this)
        binding.sbtnBack.setOnClickListener(this)
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_detail -> {
                rl.visibility = View.GONE
                switchFragment(detailFragment)
                binding.tvTitle.text = "学生作答详情"
                binding.ivDetail.visibility = View.GONE
            }

            R.id.sbtn_back -> {
                if (currentFragment is CommentDetailFragment) {
                    if (publishFragment.areTheSame()) finish() else showSaveDialog()
                } else {
                    rl.visibility = View.VISIBLE
                    supportFragmentManager.popBackStackImmediate()
                    binding.tvTitle.text = "难题讲评方案"
                    binding.ivDetail.visibility = View.VISIBLE
                    currentFragment = commentFragment
                }

            }
        }
    }

    override fun onBackPressed() {
        //原始
        if (currentFragment is CommentDetailFragment) {
            if (publishFragment.areTheSame()) finish() else showSaveDialog()
        } else {
            supportFragmentManager.popBackStackImmediate()
            binding.tvTitle.text = "难题讲评方案"
            binding.ivDetail.visibility = View.VISIBLE
            currentFragment = commentFragment
        }
    }


    override fun initData() {
        loadingDialog.show()
        if (isOneOnOne) {
            viewModel.getWrongSolutionDetail(quesId)
        } else {
            viewModel.getHardItemSolution(
                    CurrentUser.getUserID(),
                    COURSE_CLASSID,
                    CurrentUser.getSchoolID(),
                    CurrentUser.getToken(),
                    quesId!!,
                    paperId!!,
                    setId!!,
                    Ext.STAGE_NO
            )
        }
    }

    /*保存弹框*/
    private fun showSaveDialog() {
        val mLogOutDialog = LogOutDialog.Builder(this)
        mLogOutDialog.setMessage("讲评有修改，是否保存?")
                .setCancleButton("直接退出") { dialog, _ ->
                    dialog.dismiss()
                    finish()
                }
                .setEnsureButton("保存") { dialog, _ ->
                    dialog.dismiss()
//                val fmt = supportFragmentManager.findFragmentByTag("publish") as PublishFragment
                    publishFragment.upLoad(0, isOneOnOne)
                }.create().show()
    }

    private fun switchFragment(fragment: Fragment) {
        fTransition = supportFragmentManager.beginTransaction().addToBackStack(null)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        if (currentFragment != fragment) {
            fTransition.hide(currentFragment)
            currentFragment = fragment
            if (!fragment.isAdded) {
                fTransition.add(
                        R.id.fl,
                        fragment,
                        if (fragment is CommentDetailFragment) "comment" else "detail"
                ).show(fragment).commit()
            } else {
                fTransition.show(fragment).commit()
            }
        } else {
            fTransition.show(currentFragment).commit()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun startObserve() {
        viewModel.hardSolution.observe(this, Observer {
            state = it.State
            when (it.TkModel.TypeNo) {
                "Q", "V", "X", "W", "G", "b", "d", "g", "k", "f" -> binding.ivDetail.visibility =
                        View.VISIBLE
                else -> binding.ivDetail.visibility = View.GONE
            }
            if (finished) {
                binding.tvLost.text = HtmlUtils.setText(getString(R.string.readtime, it.ReadCount))
                binding.tvTime.text =
                        HtmlUtils.setText(getString(R.string.commentnum, it.PassedCount))
            } else {
                val duration = it.Duration
                QuestionListAdapter.setAnswerTime(this, duration, binding.tvTime)
                binding.tvLost.text = HtmlUtils.setText(
                        getString(R.string.lostpercent,
                                "${BigDecimal(it.ScoreRate * 100).setScale(0,
                                        BigDecimal.ROUND_HALF_UP)}%")
                )
            }
            rl.visibility = View.VISIBLE
            switchFragment(commentFragment)
        })
        viewModel.mErrorMsg.observe(this, Observer {
            MyToast.showToast(it)
            loadingDialog.dismiss()
        })
    }
}
